package com.ai.bitcoin.jpa.dao;

import com.ai.bitcoin.jpa.entity.BccUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;
import java.util.List;

public interface BccUserDao extends JpaRepository<BccUser, String> {
    /**
     * PLC发行量
     *
     * @return plc发行量
     */
    @Query("SELECT SUM(bonus) FROM BccUser ")
    long getBonusTotal();

    BccUser findByOpenId(String openId);

    //批量查找用户
    List<BccUser> findByOpenIdIn(String[] openIdList);

    @Query(nativeQuery = true, value = "SELECT count(id) from bcc_user where share_qrcode_url is not NULL")
    Integer findCountByQrcodeUrlIsNull();

    @Query(nativeQuery = true, value = "SELECT sum(bonus) from bcc_user where share_qrcode_url is not NULL")
    Double findSumByQrcodeUrlIsNull();

    @Query(nativeQuery = true, value = "update bcc_user set update_time = ?1 ,image = ?3,nickname = ?4 where open_id = ?2")
    @Modifying
    void updateUser(Date now, String openId, String image, String nickname);

    @Query(nativeQuery = true, value = "update bcc_user set share_qrcode_url = ?1 where open_id = ?2")
    @Modifying
    void updateUserQrcode(String qrcodeUrl, String openId);

    @Query(nativeQuery = true, value = "update bcc_user set update_time = ?1 ,bonus = bonus + ?2 where open_id = ?3")
    @Modifying
    void updateUserBonusByOpenId(Date now, Double bonus, String openId);

    @Query(nativeQuery = true, value = "update bcc_user set update_time = NOW() ,bonus = bonus - ?1 where open_id = ?2 AND bonus >= ?1")
    @Modifying
    int descreaseUserBonus(Double bonus, String openId);

    BccUser findBySymbol(String symbol);

    @Query(nativeQuery = true, value = "SELECT rank from (\n" +
            "  SELECT  (@i\\:=@i+1) as  rank , open_id, bonus from bcc_user ,(select @i\\:=0) as it   ORDER BY bonus desc \n" +
            ") base where base.open_id = ?1 ")
    int computeMyRank(String openId);

    @Query(nativeQuery = true, value = "SELECT rank from (\n" +
            "  SELECT  (@i\\:=@i+1) as  rank , open_id,id, bonus from bcc_user ,(select @i\\:=0) as it   ORDER BY bonus desc \n" +
            ") base where base.id = ?1 ")
    int computeMyRankByUserId(String userId);

    @Query(nativeQuery = true, value = "select count(1) from bcc_user  where parent_open_id = ?1")
    int queryByParentOpenId(String openId);

    /**
     * 验证手机号码是否存在
     *
     * @param mobile 手机号码
     * @return true 已存在 false 不存在
     */
    boolean existsByMobileAndOpenIdNot(String mobile, String currentOpenId);

    /**
     * 验证钱包地址是否存在
     *
     * @param imToken 钱包地址
     * @return true 已存在 false 不存在
     */
    boolean existsByPurseImTokenAndOpenIdNot(String imToken, String currentOpenId);
}
